package com.sihan.framework.etm.controller;


import com.sihan.framework.etm.common.cache.LocalCache;
import com.sihan.framework.etm.common.util.LocationUtils;
import com.sihan.framework.etm.common.util.SendGuoWang;
import com.sihan.framework.etm.dto.BoxDeviceInfoDTO;
import com.sihan.framework.etm.enums.CacheKeyName;
import com.sihan.framework.etm.service.business.ToolPositionService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import org.json.simple.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.framework.model.ApiResult;
import com.framework.util.JsonUtils;
import com.sihan.framework.etm.common.CommonBiz;
import com.sihan.framework.etm.vo.schema.ToolTypeStatisticsSchema;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

import static com.sihan.framework.etm.common.CacheOperatorInfo.*;

import java.io.IOException;
import java.util.Date;
import java.util.List;

@Api(tags = "外部接口调用")
@RestController
@RequestMapping("/external/v0")
@Slf4j
public class ExternalController {

	@Autowired
	private CommonBiz ommonBiz;

	@Autowired
	private ToolPositionService toolPositionService;

	@GetMapping("/classify/tool")
	@ApiOperation(value="根据工器具编号统计种类和数量",response = ToolTypeStatisticsSchema.class)
	public ApiResult<?> statisticsDeviceTools(String codes) {
		return ApiResult.success(ommonBiz.statisticsDeviceTools(codes));
	}
	
	@GetMapping("/classify/tool_type")
	@ApiOperation(value="根据工器具类型编号查询类型名称和图片",response = ToolTypeStatisticsSchema.class)
	public ApiResult<?> statisticsDeviceToolType(String codes) {
		return ApiResult.success(ommonBiz.statisticsDeviceToolTypes(codes));
	}

//	@GetMapping("/device/shutdown")
//	@ApiOperation("每次柜门关闭时统计柜子中的工器具")
//	public ApiResult<?> statisticsDeviceTools(DeviceWarehouseDTO deviceWarehouse) {
//		return ApiResult.success(ommonBiz.receiveDeviceDatas(deviceWarehouse));
//	}
//
//	@PostMapping("/device/state")
//	@ApiOperation("柜子的运行状态（温度，湿度等）")
//	public ApiResult<?> deviceRunning(List<DeviceRunningStateSchema> stats) {
//		ommonBiz.deviceRunning(stats);
//		return ApiResult.success();
//	}

	@ApiOperation(value = "工器具轨迹记录", notes = "工器具轨迹记录")
	@PostMapping("/tool/addPositionRecord")
	public ApiResult<?> addPositionRecord(@RequestBody JSONObject jsonObject){
		log.info("收到定位数据："+jsonObject.toJSONString());
		toolPositionService.addPositionRecord(jsonObject,new Date());
		return ApiResult.success();
	}

	@ApiOperation(value = "获取IC卡信息", notes = "获取IC卡信息")
	@GetMapping("/tool/getIcCardInfo")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "codeNumber", value = "数据", dataType = "String", paramType = "query",required=true)
	})
	public ApiResult<?> getIcCardInfo(String codeNum){
		log.info("收到刷卡数据："+codeNum);
		String cardLog = String.valueOf(getMapValue(CacheKeyName.CHECK_IS_READ_CARD_FLAG.getValue(), 
				CacheKeyName.CHECK_IS_READ_CARD_FLAG.getValue()));
		if("1".equals(cardLog)){
			setMapValue(CacheKeyName.IC_CARD_INFO.getValue(), codeNum);
			setMapValue(CacheKeyName.CHECK_IS_READ_CARD_FLAG.getValue(), 
					CacheKeyName.CHECK_IS_READ_CARD_FLAG.getValue());
		}
		return ApiResult.success();
	}

	@ApiOperation(value = "获取柜子设备信息", notes = "获取柜子设备信息")
	@PostMapping("/tool/getBoxDeviceInfo")
	public ApiResult<?> getBoxDeviceInfo(@RequestBody BoxDeviceInfoDTO dto){
		try {
			log.info("收到柜子命令："+JsonUtils.toJsonString(dto));
		} catch (IOException e) {
			e.printStackTrace();
		}
		ommonBiz.receiveDeviceInfo(dto);
		return ApiResult.success();
	}


	@ApiOperation(value = "计算两点坐标距离", notes = "经纬度坐标使用逗号分割-(120.1234, 30.5678)")
	@PostMapping("/tool/CalculatedDistance")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "ALngLet", value = "A点", dataType = "String", required = true),
			@ApiImplicitParam(name = "BLngLet", value = "B点", dataType = "String", required = true),
			@ApiImplicitParam(name = "unit", value = "单位-km, miles, meters, feet, cm", dataType = "String", required = true)
	})
	public ApiResult<?> CalculatedDistance(String ALngLet,String BLngLet,String unit){
		try {
			String[] a = ALngLet.split(",");
			String[] b = BLngLet.split(",");
			double num = LocationUtils.getDistance(Double.parseDouble(a[0]), Double.parseDouble(a[1]), Double.parseDouble(b[0]), Double.parseDouble(b[1]), unit);
			return ApiResult.success("两点相差:"+num+unit);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return ApiResult.success();
	}

//	/**
//	 * 向柜子设备发送命令方法
//	 * @param commandCode 命令码
//	 * @return
//	 */
//	public ApiResult<?> openAllBoxLock(String commandCode){
//		return ommonBiz.sendCommandToDevice(Integer.parseInt(commandCode));
//	}


	@SuppressWarnings("unchecked")
	@ApiOperation(value = "获取编号", notes = "获取编号")
	@PostMapping("/tool/getToolCodeInfo")
	public ApiResult<?> getToolCodeInfo(@RequestBody JSONObject jsonObject){
		log.info("收到读卡器数据："+jsonObject.toJSONString());
		ommonBiz.getToolFromRemote((List<String>)jsonObject.get("tid"),(List<String>)jsonObject.get("epc"));
		return ApiResult.success();
	}
	
	@ApiOperation(value = "获取扫描的任务信息", notes = "获取扫描的任务信息")
	@GetMapping("/orc/scan/result")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "value", value = "数据", dataType = "String", paramType = "query",required=true)
	})
	public ApiResult<?> getOrcScanResult(String value){
		log.info("收到扫描数据："+value);
		//setMapValue(CacheKeyName.CACHE_BORROW_PLAN_MASTER_KEY.getValue(),value);
		return ApiResult.success();
	}

	@ApiOperation(value = "获取千寻服务Token", notes = "获取千寻服务Token")
	@GetMapping("/send/getToken")
	public ApiResult<?> getToken() throws IOException {
		String guoWangToken = SendGuoWang.getGuoWangToken();
		return ApiResult.success(guoWangToken);
	}

	@ApiOperation(value = "手动设置千寻服务Token", notes = "手动设置千寻服务Token")
	@GetMapping("/send/setToken")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "token", value = "token", dataType = "String", paramType = "query",required=true)
	})
	public ApiResult<?> setToken(String token) throws IOException {
		LocalCache.put("GUOWANGTOKEN", token, 500);
		return ApiResult.success("设置成功");
	}


}
